package com.zzyl.intercept;

import com.zzyl.constant.Constants;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Objects;

/**
 * 小程序端Token拦截
 */
@Component
public class WechatUserInterceptor implements HandlerInterceptor {

    @Value("${zzyl.framework.jwt.base64-encoded-secret-key}")
    private String secretKey;

    @Resource
    MemberMapper memberMapper;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果token不存在 -> 证明没有登录
        String authorization = request.getHeader("authorization");
        if (Objects.isNull(authorization)) {
            response.setStatus(401);
            return false;
        }
        //如果toke存在,解析token -> 验证token合法
        try {
            Claims claims = JwtUtil.parseJWT(secretKey, authorization);
            Long userId = claims.get(Constants.JWT_USERID,Long.class);
            //把userId放进ThreadLocal中,但是ThreadLocal底层的Map是一个弱
            //引用Map,除非内存不够用,永远不会触发GC,导致内存泄漏,最终有可能内存溢出(OOM)
            UserThreadLocal.set(userId);
            Member member = memberMapper.queryById(userId);
            Objects.requireNonNull(member,"微信用户不存在");
        }catch (Exception e) {
            response.setStatus(401);
            return false;
        }
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
